// pages/firstpage/bankcard/bankcard.js
import {
  ApiRootUrl,IMG_PATH,apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import Toast from '../../../@vant/weapp/toast/toast';
import{
  request
} from "../../../utils/util"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    attachmentInfoA:{},
    attachmentInfoB:{},
    img_l:[],
    statusBarHeight:0,
    type:0,
    title:'',
    nonResidentsList:['是','否'],
    occupationCodeList:[
      {
        text:'专业技术人员',
        id:100
      },
      {
        text:'商业、服务业人员',
        id:300
      },
      {
        text:'生产、运输相关人员',
        id:500
      },
      {
        text:'办事人员及有关人员',
        id:200
      },
      {
        text:'其他',
        id:999
      },
    ],
    shownonResidents:false,
    userinfo:{},
    userSex:'',
    dueDate:'',
    contcatAddress:'',
    occupationCode:'',
    occupationText:'',
    frontAddress:'',
    reverseAddress:'',
    showoccupationCode:false,
    showDueDate:false,
    sfzzm:`${IMG_PATH}/money/sfzZm.png`,
    sfzfm:`${IMG_PATH}/money/sfzFm.png`,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let time=this.formatDate(new Date().getTime())
    let userinfo=wx.getStorageSync('userinfo')
    if (parseInt(userinfo.identity.substr(16, 1)) % 2 == 1) {
      this.setData({
        userSex:'男'
      })
    } else {
        this.setData({
          userSex:'女'
        })}
    let openId=wx.getStorageSync('openId')
    if(options.type==2){
      this.setData({
        title:'填写银行卡申请信息',
      })
    }else{
      this.setData({
        title:'填写卡号',
      })
    }
    this.setData({
      statusBarHeight:wx.getSystemInfoSync()['statusBarHeight'],
      type:options.type,
      userinfo:userinfo,
      openId:openId,
      dueDate:time
    })
  },

  getBaseA(){
    var FSM = wx.getFileSystemManager(); 
let self = this;
    //获取图片
    wx.chooseImage({
      count: 1,
      success: function(res) {
        //循环将得到的图片转换为Base64
        for (let r in res.tempFilePaths) {
          console.log(res.tempFilePaths[r])
          FSM.readFile({
            filePath: res.tempFilePaths[r],
            encoding: "base64",
            success: function(data) {
              console.log('数据',data.data)
              self.setData({
                frontAddress:data.data
              })
            }
          });
        }
      },
    })
  },
  getBaseB(){
    var FSM = wx.getFileSystemManager(); 
let self = this;
    //获取图片
    wx.chooseImage({
      count: 1,
      success: function(res) {
        //循环将得到的图片转换为Base64
        for (let r in res.tempFilePaths) {
          console.log(res.tempFilePaths[r])
          FSM.readFile({
            filePath: res.tempFilePaths[r],
            encoding: "base64",
            success: function(data) {
              console.log('数据',data.data)
              self.setData({
                reverseAddress:data.data
              })
            }
          });
        }
      },
    })
  },


  contcatAddressBlur(event){
    console.log(event);
    this.setData({
      contcatAddress: event.detail.value
    })
  },
  //点击展示时间选择
  showDueDate(){
    this.setData({
      showDueDate:true
    })
  },
  //关闭时间选择
  dueDateClose(){
    this.setData({
      showDueDate:false
    })
  },
  //格式化时间
   formatDate(value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;

    return y + '-' + MM + '-' + d;
  },
   formatDate1(value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;

    return y +  MM +  d;
  },
  //选择时间
  onInput(event) {
    console.log(event);
    console.log(this.formatDate(event.detail));
    let time=this.formatDate(event.detail)
    let time1=this.formatDate1(event.detail)
    console.log(time1);
    console.log(time);
    this.setData({
      currentDate: time,
      dueDate:time1
    });
  },
  //已有银行卡提交
  submit1(){
    let self=this
    Toast.loading({
      duration: 0,
      message: '提交中...',
      forbidClick: true,
    });
    if(!self.data.cardNum||!self.data.cardNum.length){
      Toast.clear()
      Toast.fail('请输入银行卡号')
      return
    }
    if(!self.data.openAccountAddress||!self.data.openAccountAddress.length){
      Toast.clear()
      Toast.fail('请输入开户行')
      return
    }
    if(!self.data.nonResidents||!self.data.nonResidents.length){
      Toast.clear()
      Toast.fail('请选择是否非居民')
      return
    }
    // return
    let userInfo=self.data.userinfo
    let params={
      openId:userInfo.openId,
      bankType:1,
      bankCardCode:self.data.cardNum,
      openAccountAddress:self.data.openAccountAddress,
      nonResidents:self.data.nonResidents=='是'?1:0
    }
    wx.request({
      url: `${ApiRootUrl}/bankcard/dealAddCard`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          Toast.clear();
          console.log(res.data.data);
        }else{
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  //上传照片
  chooseImgA: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(res)
        _this.setData({
          img_lA: res.tempFilePaths
        },()=>{
          _this.loadimgA()
        })
        console.info(res.tempFilePaths.length);
      }
    })
  },
  chooseImgB: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(res)
        _this.setData({
          img_lB: res.tempFilePaths
        },()=>{
          _this.loadimgB()
        })
        console.info(res.tempFilePaths.length);
      }
    })
  },
  loadimgA: function () {
    Toast.loading({
      duration: 0,
      message: '上传中...',
      forbidClick: true,
    });
    var _this = this;
    wx.uploadFile({
      url: `${ApiRootUrl}/labourMicro/uploadLabourMicro`, //接口
      filePath: _this.data.img_lA[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '上传成功',
          });
        // var data = JSON.parse(JSON.stringify(res.data));
        var data=JSON.parse(res.data)
        console.log(data);
        // return
        let obj={
          attachmentAddr:data.data.attachmentAddr,
          attachmentName:data.data.attachmentName,
          attachmentSize:data.data.attachmentSize
        }
        // arr.push(obj)
        _this.setData({
          attachmentInfoA:obj
        })
        console.log(_this.data.attachmentInfoA);
      },
      fail: function (error) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: res.data.message,
        });
        console.log(error);
      }
    })
  },
  loadimgB: function () {
    Toast.loading({
      duration: 0,
      message: '上传中...',
      forbidClick: true,
    });
    var _this = this;
    wx.uploadFile({
      url: `${ApiRootUrl}/labourMicro/uploadLabourMicro`, //接口
      filePath: _this.data.img_lB[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '上传成功',
          });
        // var data = JSON.parse(JSON.stringify(res.data));
        var data=JSON.parse(res.data)
        console.log(data);
        // return
        let obj={
          attachmentAddr:data.data.attachmentAddr,
          attachmentName:data.data.attachmentName,
          attachmentSize:data.data.attachmentSize
        }
        // let arr=[]
        // arr.push(obj)
        _this.setData({
          attachmentInfoB:obj
        })
        console.log(_this.data.attachmentInfoB);
      },
      fail: function (error) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: res.data.message,
        });
        console.log(error);
      }
    })
  },
  //申请银行卡
  submit2(){
    let self=this
    Toast.loading({
      duration: 0,
      message: '提交中...',
      forbidClick: true,
    });
    if(!self.data.contcatAddress||!self.data.contcatAddress.length){
      Toast.clear()
      Toast.fail('请输入联系地址')
      return
    }
    if(!self.data.postalCode||!self.data.postalCode.length){
      Toast.clear()
      Toast.fail('请输入邮政编码')
      return
    }
    if(!self.data.occupationText||!self.data.occupationText.length){
      Toast.clear()
      Toast.fail('请选择职业')
      return
    }
    if(!self.data.nonResidents||!self.data.nonResidents.length){
      Toast.clear()
      Toast.fail('请选择是否非居民')
      return
    }
    if(!self.data.img_lA||!self.data.img_lA.length){
      Toast.clear()
      Toast.fail('请上传正面照')
      return
    }
    if(!self.data.img_lB||!self.data.img_lB.length){
      Toast.clear()
      Toast.fail('请上传反面照')
      return
    }
    // return
    let userInfo=self.data.userinfo
    let params={
      openId:userInfo.openId,
      name:userInfo.name,
      sex:self.data.userSex=='男'?1:2,
      ceritificateType:1,
      identity:userInfo.identity,
      dueDate:self.data.dueDate,
      phone:userInfo.phone,
      contcatAddress:self.data.contcatAddress,
      postalCode:self.data.postalCode,
      occupationCode:self.data.occupationCode,
      frontAddress:self.data.attachmentInfoA.attachmentAddr,
      reverseAddress:self.data.attachmentInfoB.attachmentAddr,
      nonResidents:self.data.nonResidents=='是'?1:0,

    }
    wx.request({
      url: `${ApiRootUrl}/bankcard/updateBankCardInfo`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          Toast.clear();
          console.log(res.data.data);
        }else{
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  showoccupationCode(){
    this.setData({
      showoccupationCode:true
    })
  },
  occupationCodeClose(){
    this.setData({
      showoccupationCode:false
    })
  },
  occupationCodeConfirm(e){
    console.log(e);
    this.setData({
      showoccupationCode:false,
      occupationCode:e.detail.value.id,
      occupationText:e.detail.value.text
    })
  },
  shownonResidents(){
    this.setData({
      shownonResidents:true
    })
  },
  nonResidentsClose(){
    this.setData({
      shownonResidents:false
    })
  },
  nonResidentsConfirm(e){
    console.log(e);
    this.setData({
      shownonResidents:false,
      nonResidents:e.detail.value
    })
  },
  //返回上一页
  backClick(){
    wx.navigateBack()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})